package com.agrishare.service.impl;

import com.agrishare.entity.PointRecord;
import com.agrishare.entity.PointType;
import com.agrishare.entity.User;
import com.agrishare.repository.PointRecordRepository;
import com.agrishare.repository.UserRepository;
import com.agrishare.service.PointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional
public class PointServiceImpl implements PointService {
    
    @Autowired
    private PointRecordRepository pointRecordRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public void addPoints(User user, PointType type, String description, Long relatedId) {
        // 检查是否已经获得过相同类型的积分（避免重复获得）
        if (relatedId != null && pointRecordRepository.existsByUserAndTypeAndRelatedIdAndCreatedAtAfter(
                user, type, relatedId, LocalDateTime.now().minusDays(1))) {
            return;
        }
        
        PointRecord record = new PointRecord();
        record.setUser(user);
        record.setType(type);
        record.setPoints(type.getDefaultPoints());
        record.setDescription(description);
        record.setRelatedId(relatedId);
        
        pointRecordRepository.save(record);
        
        // 更新用户总积分
        user.setPoints(user.getPoints() + type.getDefaultPoints());
        userRepository.save(user);
    }
    
    @Override
    public void addRegisterPoints(User user) {
        addPoints(user, PointType.REGISTER, "注册奖励", null);
    }
    
    @Override
    public void addPostPoints(User user, Long postId) {
        addPoints(user, PointType.POST_CREATE, "发布帖子", postId);
    }
    
    @Override
    public void addCommentPoints(User user, Long commentId) {
        addPoints(user, PointType.COMMENT_CREATE, "发表评论", commentId);
    }
    
    @Override
    public void addLikePoints(User user, Long relatedId, PointType type) {
        String description = type == PointType.POST_LIKE ? "帖子被点赞" : "评论被点赞";
        addPoints(user, type, description, relatedId);
    }
    
    @Override
    public void addEssencePoints(User user, Long postId) {
        addPoints(user, PointType.POST_ESSENCE, "帖子被加精", postId);
    }
    
    @Override
    public void addExpertAnswerPoints(User user, Long postId) {
        addPoints(user, PointType.EXPERT_ANSWER, "专家解答", postId);
    }
    
    @Override
    public Page<PointRecord> getUserPointRecords(User user, Pageable pageable) {
        return pointRecordRepository.findByUser(user, pageable);
    }
    
    @Override
    public Integer getUserTotalPoints(User user) {
        Integer total = pointRecordRepository.getTotalPointsByUser(user);
        return total != null ? total : 0;
    }
}